var orderList = document.querySelector('#orders .order-list');
var orderTotalSpan = document.getElementById('order-total');

// 初始化订单页面
function initOrders() {
    const orders = JSON.parse(localStorage.getItem('orders')) || [];
    orders.forEach(orderInfo => {
        addOrder(orderInfo);
    });
    calculateOrderTotal();
}

// 添加订单到页面
function addOrder(orderInfo) {
    const orderHTML = `
        <div class="order">
            <div class="info">
                <img src="${orderInfo.imgSrc}" width="80" style="border-radius: 8px;">
                <p>${orderInfo.name}</p>
            </div>
            <div class="pic">${orderInfo.price}</div>
            <div class="num">${orderInfo.quantity}</div>
            <div class="rmb">${(orderInfo.price * orderInfo.quantity).toFixed(2)}</div>
            <div class="action">
                <button class="delete-btn">删除</button>
            </div>
        </div>
    `;
    orderList.insertAdjacentHTML('beforeend', orderHTML);
    
    // 为删除按钮添加点击事件
    const deleteBtn = orderList.lastElementChild.querySelector('.delete-btn');
    deleteBtn.addEventListener('click', () => {
        deleteOrder(deleteBtn.closest('.order'));
    });
}

// 删除订单
function deleteOrder(orderElement) {
    const orderIndex = Array.from(orderList.children).indexOf(orderElement);
    const orders = JSON.parse(localStorage.getItem('orders')) || [];
    orders.splice(orderIndex, 1);
    localStorage.setItem('orders', JSON.stringify(orders));
    
    orderElement.remove();
    calculateOrderTotal();
}

// 计算订单总金额
function calculateOrderTotal() {
    let sum = 0;
    const orders = document.querySelectorAll('.order');
    orders.forEach(order => {
        const rmb = order.querySelector('.rmb');
        sum += parseFloat(rmb.innerText);
    });
    orderTotalSpan.innerText = sum.toFixed(2);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initOrders);